import api from "@/api/auth";
interface UploadOptions {
  file: File;
  onProgress?: (percent: number) => void;
  onSuccess?: (url: string) => void;
  onError?: (error: string) => void;
  preserveFilename?: boolean;
  partialToken?: string;
}

interface UploadExtraOptions {
  preserveFilename?: boolean;
  partialToken?: string;
}

/**
 * 上传文件到七牛云
 */
export const uploadToQiniu = (options: UploadOptions) => {
  const {
    file,
    onProgress,
    onSuccess,
    onError,
    preserveFilename = false,
    partialToken
  } = options;

  const credentialPromise = partialToken
    ? api.qiniuPartial(partialToken)
    : api.qiniu();

  credentialPromise
    .then(res => {
      if (res.code === 200) {
        const { uploadToken, domain, uploadUrl } = res.data;
        const formData = new FormData();
        formData.append("file", file);
        formData.append("token", uploadToken);

        if (preserveFilename) {
          formData.append("key", file.name);
        }

        const xhr = new XMLHttpRequest();
        xhr.open("POST", uploadUrl);

        xhr.upload.onprogress = e => {
          if (e.lengthComputable && onProgress) {
            const percent = Math.round((e.loaded * 100) / e.total);
            onProgress(percent);
          }
        };

        xhr.onload = () => {
          if (xhr.status === 200) {
            try {
              const result = JSON.parse(xhr.responseText);
              const separator = domain.endsWith("/") ? "" : "/";
              const url = domain + separator + (result.key || result.hash);
              if (onSuccess) onSuccess(url);
            } catch (e) {
              if (onError) onError("解析响应失败");
            }
          } else {
            if (onError) onError("上传失败");
          }
        };

        xhr.onerror = () => {
          if (onError) onError("网络错误");
        };

        xhr.send(formData);
      } else {
        if (onError) onError("获取上传凭证失败");
      }
    })
    .catch(err => {
      if (onError) onError("获取上传凭证失败: " + err.message);
    });
};

/**
 * 通用文件上传函数，支持 Element Plus 上传组件
 */
export const uploadFile = (
  options: any,
  onProgress?: (percent: number) => void,
  onSuccess?: (url: string) => void,
  onError?: (error: string) => void,
  extraOptions?: UploadExtraOptions
) => {
  const { file } = options;
  uploadToQiniu({
    file,
    onProgress,
    onSuccess: url => {
      if (onSuccess) onSuccess(url);
    },
    onError: error => {
      if (onError) onError(error);
    },
    preserveFilename: extraOptions?.preserveFilename ?? false,
    partialToken: extraOptions?.partialToken
  });
};
